import { def } from './utils';

const arrayPrototype = Array.prototype;

export const arrayMethods = Object.create(arrayPrototype);

const methodsNeedChange = [
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
];

methodsNeedChange.forEach(methodName => {
  // 备份方法
  const original = arrayPrototype[methodName];

  // 定义新的方法
  def(arrayMethods, methodName, function () {
    // 取出__ob__
    const ob = this.__ob__;
    // 三种方法push、ubshift、splice会插入新值
    let inserted = [];
    let args = [...arguments];
    switch (methodName) {
      case 'push':
      case 'unshift':
        inserted = args;
        break;
      case 'splice':
        inserted = args.slice(2);
        break;
    }
    if (inserted) {
      // 让新增的值也变得响应
      ob.observeArray(inserted);
      ob.dep.notify();
    }

    // 恢复原来的功能
    let result = original.apply(this, arguments);

    return result;
  }, false);
})